package edu.xpu.project.record.controller;

import java.io.IOException;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.xpu.project.log.entity.DriverLog;
import edu.xpu.project.log.entity.SchoolBusLog;
import edu.xpu.project.log.service.DriverLogService;
import edu.xpu.project.log.service.SchoolBusLogService;
import edu.xpu.project.record.entity.AssignBusRecord;
import edu.xpu.project.record.entity.BusBespeakRecord;
import edu.xpu.project.record.service.AssignBusRecordService;
import edu.xpu.project.record.service.BusBespeakRecordService;
import edu.xpu.project.user.entity.DriverEntity;
import edu.xpu.project.user.entity.ProjectUser;
import edu.xpu.project.vehicle.entity.BusSchedule;
import edu.xpu.project.vehicle.entity.SchoolBus;
import edu.xpu.project.vehicle.service.BusScheduleService;
import edu.xpu.project.vehicle.service.SchoolBusService;


/**
 * @describe 校车派车记录控制器
 * @author liukang
 * @date 2017年5月13日
 */
@Controller
@RequestMapping(value="assignBusRecord")
public class AssignBusRecordController {
	
	@Autowired
	private AssignBusRecordService assignBusRecordService;
	@Autowired
	private BusScheduleService busScheduleService;
	@Autowired
	private BusBespeakRecordService busBespeakRecordService;
	@Autowired
	private SchoolBusService schoolBusService;
	//日志service
	@Autowired
	private SchoolBusLogService busLogService;
	@Autowired
	private DriverLogService driverLogService;
	
	@ResponseBody
	@RequestMapping(value="getSchoolInfoByStatusAndCurrentplace/{scheduleId}", produces={"application/json; charset=utf-8"})
	public String getSchoolInfoByStatusAndCurrentplace(@PathVariable(value="scheduleId") Long scheduleId) {
		BusSchedule busSchedule = busScheduleService.get(scheduleId);
		Integer startStation = busSchedule.getStartStation();
		List<SchoolBus> schoolBusByStatus = schoolBusService.getSchoolBusByStatusAndCurrentPlace(1, startStation);
		ObjectMapper objectMapper = new ObjectMapper();
		String schoolbusJson = "1";
		try {
			schoolbusJson= objectMapper.writeValueAsString(schoolBusByStatus);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return schoolbusJson;
	}
	
	/**
	  * @MethodName: resetBusByScheduleId
	  * @Description: 发车完成, 重置所有状态
	  * @Author liukang
	  * @date 2017年5月24日  下午3:13:00
	 */
	@ResponseBody
	@RequestMapping(value="resetBusByScheduleId/{assignId}")
	public String resetBusByScheduleId(@PathVariable(value="assignId") Long assignId) {
		AssignBusRecord assignBusRecord = assignBusRecordService.get(assignId);
		//进行发车行为
		if (assignBusRecord != null) {
			assignBusRecord.setStatus(3);	//发车完成
			String schoolBusIds = assignBusRecord.getSchoolBusIds();
			String[] busIds = schoolBusIds.split(",");
			for (int i = 0, len = busIds.length; i < len; i++) {
				SchoolBus schoolBus = schoolBusService.get(Long.parseLong(busIds[i]));
				if (schoolBus != null) {
					schoolBus.setStatus(1);		//已发车完成
					//设置校车的起点和终点站（应该有变化）
					BusSchedule busSchedule = assignBusRecord.getBusSchedule();
					Integer endStation = busSchedule.getEndStation();
					//重置当前位置
					schoolBus.setLocalStatus(endStation);
					schoolBusService.saveOrUpdate(schoolBus);
				}
			}
			AssignBusRecord saveOrUpdate = assignBusRecordService.saveOrUpdate(assignBusRecord);
			if (saveOrUpdate != null) {
				return "{\"status\":\"success\"}";
			}
		}
		return "{\"status\":\"error\"}";
	}
	
	/**
	  * @MethodName: startBusByScheduleId
	  * @Description: 发车
	  * @Author liukang
	  * @date 2017年5月24日  下午2:56:19
	 */
	@ResponseBody
	@RequestMapping(value="startBusByScheduleId/{assignId}")
	public String startBusByScheduleId(@PathVariable(value="assignId") Long assignId,
			@ModelAttribute("sessionUser") ProjectUser user) {
		AssignBusRecord assignBusRecord = assignBusRecordService.get(assignId);
		//进行发车行为
		if (assignBusRecord != null) {
			assignBusRecord.setStatus(2);
			String schoolBusIds = assignBusRecord.getSchoolBusIds();
			String[] busIds = schoolBusIds.split(",");
			for (int i = 0, len = busIds.length; i < len; i++) {
				SchoolBus schoolBus = schoolBusService.get(Long.parseLong(busIds[i]));
				if (schoolBus != null) {
					schoolBus.setStatus(3);		//发车中
					//设置校车的起点和终点站（应该有变化）
					schoolBusService.saveOrUpdate(schoolBus);
					Date date = new Date();
					//获取校车的司机, 设置校车日志
					SchoolBusLog busLog = new SchoolBusLog();
					busLog.setCreateDate(date);
					busLog.setCreatePersonId(user.getId());
					busLog.setSchoolBus(schoolBus);
					busLogService.saveOrUpdate(busLog);
					
					DriverEntity driverEntity = schoolBus.getDriverEntity();
					if (driverEntity != null) {
						//设置司机日志
						DriverLog driverLog = new DriverLog();
						driverLog.setCreateDate(date);
						driverLog.setCreatePersonId(user.getId());
						driverLog.setDriverEntity(driverEntity);
						driverLogService.saveOrUpdate(driverLog);
					}
					
				}
			}
			AssignBusRecord saveOrUpdate = assignBusRecordService.saveOrUpdate(assignBusRecord);
			if (saveOrUpdate != null) {
				return "{\"status\":\"success\"}";
			}
		}
		return "{\"status\":\"error\"}";
	}
	
	/**
	  * @MethodName: assignBusRecordDetails
	  * @Description: 校车派遣记录
	  * @Author liukang
	  * @date 2017年5月23日  下午12:24:36
	 */
	@RequestMapping(value="assignBusRecordDetails/{id}")
	public String assignBusRecordDetails(@PathVariable(value="id") Long id, ModelMap modelMap) {
		AssignBusRecord assignBusRecord = assignBusRecordService.get(id);
		modelMap.addAttribute("assignBusRecord", assignBusRecord);
		return "record/assignBus/assignBusRecordDetail";
	}
	
	/**
	 * @describe 派车记录删除
	 * @date 2017年5月23日
	 * @author liukang
	 */
	@ResponseBody
	@RequestMapping(value="assignBusRecordDel/{id}")
	public String assignBusRecordDel(@PathVariable(value="id") Long id) {
		try {
			assignBusRecordService.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			return "{\"status\":\"error\"}";
		}
		return "{\"status\":\"success\"}";
	}
	
	
	/**
	 * @describe 添加校车派遣记录
	 * @date 2017年5月14日
	 * @author liukang
	 */
	@ResponseBody
	@RequestMapping(value="/saveAssignBusRecord/{scheduleId}")
	public String saveAssignBusRecord(@PathVariable(value="scheduleId") Long scheduleId,
			@RequestParam(value="busIds") String busIds,
			@ModelAttribute(value="sessionUser") ProjectUser user) {
		//解析校车ids
		String[] ids = busIds.split(",");
		//保存记录信息
		BusSchedule busSchedule = busScheduleService.get(scheduleId);
		AssignBusRecord assignBusRecord = new AssignBusRecord();
		assignBusRecord.setCreateDate(new Date());
		assignBusRecord.setCreatePersonId(user.getId());
		assignBusRecord.setCreatePersonName(user.getName());
		assignBusRecord.setBusSchedule(busSchedule);
		assignBusRecord.setStatus(1);
		assignBusRecord.setSchoolBusIds(busIds);
		//更新车辆信息
		for (int i = 0, len = ids.length; i < len; i++) {
			SchoolBus schoolBus = schoolBusService.get(Long.parseLong(ids[i]));
			if (schoolBus != null) {
				schoolBus.setStatus(2);
				schoolBusService.saveOrUpdate(schoolBus);
			}
		}
		//修改预约记录的状态
		Set<BusBespeakRecord> bespeakRecords = busSchedule.getBespeakRecords();
		for (BusBespeakRecord busBespeakRecord : bespeakRecords) {
			busBespeakRecord.setStatus(2);
			busBespeakRecordService.saveOrUpdate(busBespeakRecord);
		}
		//对预约的人员状态进行更新
		/*for (ProjectUser pUser : projectUsers) {
			
		}*/
		AssignBusRecord saveOrUpdate = assignBusRecordService.saveOrUpdate(assignBusRecord);
		if (saveOrUpdate == null) {
			return "{\"status\":\"error\"}";
		}
		return "{\"status\":\"success\"}";
	}
	
	/**
	  * @MethodName: toAssignBusRecordPage
	  * @Description: 跳转到校车派遣页面
	  * @param modelMap
	  * @return String    返回类型
	 * @throws ParseException 
	  * @throws
	  * @Author liukang
	  * @date 2017年5月19日  下午6:18:55
	 */
	@RequestMapping(value="toAssignBusRecordPage")
	public String toAssignBusRecordPage(ModelMap modelMap, @RequestParam(value="dateFlag", defaultValue="0") Integer dateFlag,
			@RequestParam(value="currentDate", required=false) String currentDate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//统计信息，进行计算, 给予管理员参考值
		//1、获取一个校车时刻表, 以及在该时刻申请的教师详情
		List<BusSchedule> busScheduleList = busScheduleService.findAll();
		//2、获取每一个时刻申请的教师(默认今天的)
		String formatDate = sdf.format(new Date());
		if (dateFlag == 1) {			//前一天
			Date parse = sdf.parse(currentDate);
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(parse);
			calendar.add(Calendar.DATE, 1);
			parse = calendar.getTime();
			formatDate = sdf.format(parse);
		} else if (dateFlag == -1) {	//后一天
			Date parse = sdf.parse(currentDate);
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(parse);
			calendar.add(Calendar.DATE, -1);
			parse = calendar.getTime();
			formatDate = sdf.format(parse);
		}
		List<Object> busSchedulePersonNum = busBespeakRecordService.getBusSchedulePersonNum(formatDate);
		//3、处理两个list
		if (busScheduleList != null) {
			for (int i = 0, len = busScheduleList.size(); i < len; i++) {
				//车次id
				Long busScheduleId = busScheduleList.get(i).getId();
				//ArrayList<BusBespeakRecord> arrayList = null;
				if (busSchedulePersonNum != null) {
					for (int j = 0, recordLen = busSchedulePersonNum.size(); j < recordLen; j++) {
						Object[] tmpArr = (Object[]) busSchedulePersonNum.get(j);
						BigInteger idObj = (BigInteger) tmpArr[0];
						BigInteger personNumObj = (BigInteger) tmpArr[1];
						//判断车次id
						if (busScheduleId == idObj.longValue()) {
							busScheduleList.get(i).setPersonNum(personNumObj.intValue());
							//设置状态
						}
					}
				}
				modelMap.addAttribute("currentDate", formatDate);
				//获取当前车的状态, 也就是这一天的状态
				List<AssignBusRecord> records = assignBusRecordService.getRecordsByBusScheduleIdAndTime(busScheduleId, formatDate);
				if (records != null && records.size() != 0) {
					busScheduleList.get(i).setCurrentStatus(2);
				}
			}
		}
		
		modelMap.addAttribute("busScheduleList", busScheduleList);
		return "record/assignBus/assignBusAdd";
	}
	
	/**
	 * @describe 指派校车list
	 * @date 2017年5月14日
	 * @author liukang
	 */
	@RequestMapping(value="assignBusRecordList")
	public String assignBusRecordList(@RequestParam(value="pageNumber", defaultValue="1", required=false) String pageNumber,
			@RequestParam(value="pageSize", defaultValue="10", required=false) String pageSize,
			AssignBusRecord assignBusRecord, ModelMap modelMap) {
		Page<AssignBusRecord> pageByCriterias = assignBusRecordService.getPageByCriterias(pageNumber, pageSize, assignBusRecord);
		modelMap.addAttribute("page", pageByCriterias)
				.addAttribute("assignBusRecord", assignBusRecord)
				.addAttribute("number", pageNumber)
				.addAttribute("size", pageSize);
		return "record/assignBus/assignBusList";
	}

}
